package com.jiliang.common.area;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.jiliang.common.constant.CommonDsConstant;
import com.jiliang.common.http.HttpClientDsUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 高德请求API
 *
 * @author 
 * @version v_1.0.1
 * @since 2018/8/10 15:41
 */
public class AliMapDsUtil {

    private static Logger LOGGER = LoggerFactory.getLogger(AliMapDsUtil.class);

    private static String isString(String str) {
        if (StringUtils.isEmpty(str) || str.contains(AliMapDsConstant.STRING_SQUARE_BRACKETS)) {
            return "";
        }
        return str;
    }

    private static String getJson(String json, String node) {
        JSONObject object = JSONObject.parseObject(json);
        String info = object.getString(node);
        return info;
    }


    public static Map<String, String> getAreaMap(String location,String key) {
        Map<String, String> map = new HashMap<String, String>(16);
        String url="http://restapi.amap.com/v3/geocode/regeo?output=json&key="+key+"&radius=1000&location=";
        LOGGER.info("请求地址:" + url + location);
        String result = HttpClientDsUtil.doPost(url + location);
        LOGGER.info("高德返回结果:" + result);
        if (!StringUtils.isEmpty(result)) {
            String info = getJson(result, AliMapDsConstant.NODE_NAME_INFO);
            if (info.equals(AliMapDsConstant.NODE_NAME_YES)) {
                String obj = getJson(result, AliMapDsConstant.NODE_NAME_REREG);
                String addrs = getJson(obj, AliMapDsConstant.NODE_NAME_ADDR);
                LOGGER.info("详细地址信息:" + addrs);
                String prov = getJson(addrs, AliMapDsConstant.NODE_NAME_PROV);
                String city = getJson(addrs, AliMapDsConstant.NODE_NAME_CITE);
                String dist = getJson(addrs, AliMapDsConstant.NODE_NAME_DIST);
                if (AreaDsConstant.ZHIXIASHI_NAME.contains(prov) && dist.contains(AreaDsConstant.QU)) {
                    city = AreaDsConstant.SHIXIAQU;
                } else if (AreaDsConstant.ZHIXIASHI_NAME.contains(prov) && dist.contains(AreaDsConstant.XIAN)) {
                    city = AreaDsConstant.SHENGZHIXIAXIAN;
                }
                map.put(AliMapDsConstant.NODE_NAME_PROV, prov);
                map.put(AliMapDsConstant.NODE_NAME_CITE, city);
                map.put(AliMapDsConstant.NODE_NAME_DIST, dist);
                String township = getJson(addrs, "township");
                String streetNumber = getJson(addrs, AliMapDsConstant.NODE_NAME_STREETNUMBER);
                String street = getJson(streetNumber, "street");
                String number = getJson(streetNumber, "number");
                map.put(AliMapDsConstant.NODE_NAME_STREETNUMBER, isString(township) + isString(street) + isString(number));
            }

        }
        return map;
    }
    /**
     * 根据地址信息获取经纬度
     */
    public static List<AreaResDsBean> getAreaToLngAndlat(String addr,String key) {
        List<AreaResDsBean>  areaResDsBeanList = new ArrayList<>();
        String url="https://restapi.amap.com/v3/geocode/geo?output=json&key="+key+"&address=";
        LOGGER.info("请求地址:" + url + addr);
        String result = HttpClientDsUtil.doGet(url + addr);
        LOGGER.info("高德返回结果:" + result);
        if (!StringUtils.isEmpty(result)) {
            String info = getJson(result, AliMapDsConstant.NODE_NAME_INFO);
            if (info.equals(AliMapDsConstant.NODE_NAME_YES)) {
                String obj = getJson(result, AliMapDsConstant.NODE_NAME_GEOCODES);
                JSONArray objects = JSON.parseArray(obj);
                if (objects == null || objects.size() <= 0) {
                    return areaResDsBeanList;
                }
                for (int i = 0; i < objects.size(); i++) {
                    AreaResDsBean areaResDsBean = new AreaResDsBean();
                    JSONObject jsonObject = objects.getJSONObject(i);
                    String addrName = jsonObject.getString(AliMapDsConstant.NODE_NAME_FORMATTED_ADDRESS);
                    areaResDsBean.setAreaFullName(addrName);
                    String location = jsonObject.getString(AliMapDsConstant.NODE_NAME_LOCATION);
                    String[] str =location.split(",");
                    if(str.length > 0){
                        //经度
                        areaResDsBean.setLongitude(str[0]);
                        //纬度
                        areaResDsBean.setLatitude(str[1]);
                    }
                    areaResDsBeanList.add(areaResDsBean);
                }
            }

        }
        return areaResDsBeanList;
    }
    /**
     * 根据经纬度获取地址信息
     */
    public static Map<String, String> getLngAndlatToArea(String location,String key) {
        Map<String, String> map = new HashMap<>(16);
        String url="https://restapi.amap.com/v3/geocode/regeo?output=json&radius=500&key="+key+"&location=";
        LOGGER.info("请求地址:" + url + location);
        String result = HttpClientDsUtil.doGet(url + location);
        LOGGER.info("高德返回结果:" + result);
        if (!StringUtils.isEmpty(result)) {
            String info = getJson(result, AliMapDsConstant.NODE_NAME_INFO);
            if (info.equals(AliMapDsConstant.NODE_NAME_YES)) {
                String obj = getJson(result, AliMapDsConstant.NODE_NAME_REGEOCODE);
                if (StringUtils.isEmpty(obj)) {
                    return map;
                }
                JSONObject jsonObject = JSONObject.parseObject(obj);
                String addrName = jsonObject.getString(AliMapDsConstant.NODE_NAME_FORMATTED_ADDRESS);
                map.put(AliMapDsConstant.NODE_NAME_FORMATTED_ADDRESS, addrName);
                String addrs = getJson(obj, AliMapDsConstant.NODE_NAME_ADDR);
                LOGGER.info("详细地址信息:" + addrs);
                String prov = getJson(addrs, AliMapDsConstant.NODE_NAME_PROV);
                String city = getJson(addrs, AliMapDsConstant.NODE_NAME_CITE);
                String dist = getJson(addrs, AliMapDsConstant.NODE_NAME_DIST);
                if (AreaDsConstant.ZHIXIASHI_NAME.contains(prov) && dist.contains(AreaDsConstant.QU)) {
                    city = AreaDsConstant.SHIXIAQU;
                } else if (AreaDsConstant.ZHIXIASHI_NAME.contains(prov) && dist.contains(AreaDsConstant.XIAN)) {
                    city = AreaDsConstant.SHENGZHIXIAXIAN;
                }
                map.put(AliMapDsConstant.NODE_NAME_PROV, prov);
                map.put(AliMapDsConstant.NODE_NAME_CITE, city);
                map.put(AliMapDsConstant.NODE_NAME_DIST, dist);
                String township = getJson(addrs, "township");
                map.put("township", township);
                String streetNumber = getJson(addrs, AliMapDsConstant.NODE_NAME_STREETNUMBER);
                String street = getJson(streetNumber, "street");
                String number = getJson(streetNumber, "number");
                map.put(AliMapDsConstant.NODE_NAME_STREETNUMBER, isString(township) + isString(street) + isString(number));
            }

        }
        return map;
    }

    public static AreaResDsBean getLngAndlatToArea(String longitude, String latitude, String key) {
        Map<String, String> map = new HashMap<>(16);
        AreaResDsBean areaResDsBean = new AreaResDsBean();
        String url="https://restapi.amap.com/v3/geocode/regeo?output=json&radius=500&key="+key+"&location=";
        LOGGER.info("请求地址:" + url + longitude + CommonDsConstant.DELIMITER_DH + latitude);
        String result = HttpClientDsUtil.doGet(url + longitude + CommonDsConstant.DELIMITER_DH + latitude);
        LOGGER.info("高德返回结果:" + result);
        if (!StringUtils.isEmpty(result)) {
            String info = getJson(result, AliMapDsConstant.NODE_NAME_INFO);
            if (info.equals(AliMapDsConstant.NODE_NAME_YES)) {
                String obj = getJson(result, AliMapDsConstant.NODE_NAME_REGEOCODE);
                if (StringUtils.isEmpty(obj)) {
                    return new AreaResDsBean();
                }
                JSONObject jsonObject = JSONObject.parseObject(obj);
                // 详细地址
                String addrName = jsonObject.getString(AliMapDsConstant.NODE_NAME_FORMATTED_ADDRESS);
                areaResDsBean.setAddrName(addrName);
                // 地区信息
                String areaComponent = getJson(obj, AliMapDsConstant.NODE_NAME_ADDR);
                String prov = getJson(areaComponent, AliMapDsConstant.NODE_NAME_PROV);
                String city = getJson(areaComponent, AliMapDsConstant.NODE_NAME_CITE);
                String dist = getJson(areaComponent, AliMapDsConstant.NODE_NAME_DIST);
                if (AreaDsConstant.ZHIXIASHI_NAME.contains(prov) && dist.contains(AreaDsConstant.QU)) {
                    city = AreaDsConstant.SHIXIAQU;
                } else if (AreaDsConstant.ZHIXIASHI_NAME.contains(prov) && dist.contains(AreaDsConstant.XIAN)) {
                    city = AreaDsConstant.SHENGZHIXIAXIAN;
                }
                areaResDsBean.setProvince(prov);
                areaResDsBean.setCity(city);
                areaResDsBean.setDistrict(dist);
                // 地区编码
                String adcode = getJson(areaComponent, AliMapDsConstant.NODE_NAME_ADCODE);
                areaResDsBean.setAdcode(adcode);
                // 街道
                String township = getJson(areaComponent, "township");
                areaResDsBean.setTownship(township);
                // 街道门牌号
                String streetNumber = getJson(areaComponent, AliMapDsConstant.NODE_NAME_STREETNUMBER);
                String street = getJson(streetNumber, "street");
                String number = getJson(streetNumber, "number");
                areaResDsBean.setStreetNumber(isString(township) + isString(street) + isString(number));
            }

        }
        return areaResDsBean;
    }

    /**
     * 根据输入地址关键字提示地址信息详情
     */
    public static List<AreaResDsBean> getkeyWordsToAreaList(String addr,String key) {
        List<AreaResDsBean> resDsBeans = new ArrayList<>();
        String url="https://restapi.amap.com/v3/assistant/inputtips?output=json&key="+key+"&keywords=";
        LOGGER.info("请求地址:" + url + addr);
        String result = HttpClientDsUtil.doGet(url + addr);
        LOGGER.info("高德返回结果:" + result);
        if (!StringUtils.isEmpty(result)) {
            //String info = getJson(result, AliMapDsConstant.NODE_NAME_INFO);
            JSONObject object = JSONObject.parseObject(result);
            String info = object.getString(AliMapDsConstant.NODE_NAME_INFO);
            if (info.equals(AliMapDsConstant.NODE_NAME_YES)) {
                String obj = object.getString(AliMapDsConstant.NODE_NAME_TIPS);
                JSONArray jsonArray = JSONArray.parseArray(obj);
                for(int i = 0; i<jsonArray.size();i++){
                    AreaResDsBean areaResDsBean = new AreaResDsBean();
                    JSONObject strJson = jsonArray.getJSONObject(i);
                    String name = strJson.getString("name");
                    String district = strJson.getString("district");
                    String address = strJson.getString("address");
                    String location = strJson.getString(AliMapDsConstant.NODE_NAME_LOCATION);
                    String[] str =location.split(",");
                    if(str.length > 0){
                        //经度
                        areaResDsBean.setLongitude(str[0]);
                        //维度
                        areaResDsBean.setLatitude(str[1]);
                    }
                    areaResDsBean.setDescription(name);
                    areaResDsBean.setAreaFullName(district);
                    areaResDsBean.setAreaName(address);
                    resDsBeans.add(areaResDsBean);
                }
            }
        }
        return resDsBeans;
    }

    public static Map<String, String> getAreaMap(BigDecimal lng, BigDecimal lat, Boolean isDIST,String key) {
        Map<String, String> addrMap = getAreaMap(lng + "," + lat,key);
        if (addrMap.isEmpty()) {
            LOGGER.info("未获取到定位信息");
            return null;
        }
        String addrName = "";
        if (addrMap.containsKey(AliMapDsConstant.NODE_NAME_PROV)) {
            addrName = addrMap.get(AliMapDsConstant.NODE_NAME_PROV);
        }
        if (addrMap.containsKey(AliMapDsConstant.NODE_NAME_CITE)) {
            if (addrName.length() > 0) {
                addrName = addrName + "/" + addrMap.get(AliMapDsConstant.NODE_NAME_CITE);
            } else {
                addrName = addrMap.get(AliMapDsConstant.NODE_NAME_CITE);
            }
        }
        if (isDIST) {
            if (addrMap.containsKey(AliMapDsConstant.NODE_NAME_DIST)) {
                if (addrName.length() > 0) {
                    addrName = addrName + "/" + addrMap.get(AliMapDsConstant.NODE_NAME_DIST);
                } else {
                    addrName = addrMap.get(AliMapDsConstant.NODE_NAME_DIST);
                }
            }
        }
//        AreaResDsBean areaResDsBean = BasicDsUtil.selAreaByFullName(addrName);
//        if (areaResDsBean != null){
//            Integer id = areaResDsBean.getAreaId();
//            addrMap.put(AliMapDsConstant.NODE_NAME_AREAID, id.toString());
//            LOGGER.info("结果地区信息集合:" + addrMap);
//            return addrMap;
//        }
        LOGGER.info("未获取到地区名称");
        return null;
    }


    public static void main(String[] args) {
//        Map<String, String> map = null;
//        try {
//            map = getAreaMap(new BigDecimal(115.381508), new BigDecimal(30.778714), true,"8bc6ff93be92f6e955c00c13b9a569f5");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        Map<String, String> lngAndlatToArea = getLngAndlatToArea("116.481488,39.990464",
                "8bc6ff93be92f6e955c00c13b9a569f5");
        System.out.println(lngAndlatToArea);
    }
}
